//
//  ICChnController.m
//  ICome
//
//  Created by Administrator on 2016/11/4.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICChnController.h"

#import "ICGroup.h"
#import "ICChnMessageCell.h"
#import "ICChnModel.h"
#import "ICNotify.h"
#import "ICJSBridgeTools.h"
#import "ICApplicationModel.h"
#import "ICMessageModel.h"

@interface ICChnController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSMutableArray *dataList;
@property (nonatomic, strong) NSMutableArray * messages;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ICGroup *group;

@end

@implementation ICChnController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.group = self.parameterDictionary[@"group"];
    
    [self setupUI];
    
    [self getChanceDataSource];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [ICMessageDatabase updateGroupUnreadMessageCountWithGroupId:self.group.gId count:0]; // 清除未读数
    [ICMessageHelper updateGroupReadWithGroupId:self.group.gId];
}

- (void)setupUI {
    self.title = @"机会";
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
}

- (void)loadNewData
{
    [self.tableView.mj_header beginRefreshing];
    WEAKSELF;
    
    ICMessageFrame *firstMessageF = [self.dataList firstObject];
    [ICMessageDatabase selectMessageWithCount:LoadMessageCount group:self.group.gId firstMessage:firstMessageF.model.message finish:^(NSArray *array, NSError *error) {
        if (array.count > 0) {
            
            [weakSelf.dataList addObjectsFromArray:array];
            NSArray* reversedArray = array ;
            NSMutableArray * messgeArray = [NSMutableArray array];
            //用来记录上一条消息模型
//            ICChnModel * lastMessage = nil;
            for(ICMessageFrame *messageFrame in reversedArray)
            {
                ICChnModel * model  = [ICChnModel mj_objectWithKeyValues:[NSDictionary dictionaryWithJsonString:messageFrame.model.message.fileKey]];
                model.time = [ICMessageHelper timeFormatWithDate2:messageFrame.model.message.date];
                model.hideTime = NO;//[model.time isEqualToString:lastMessage.time];
                model.lnk = messageFrame.model.message.lnk;
//                model.title = [NSString stringWithFormat:@"%@,%@",messageFrame.model.message.messageId,model.title];
                [messgeArray addObject:model];
//                lastMessage = model;
                NSLog(@"hideTime %@",model.hideTime? @"Y":@"N");
            }
            [weakSelf.messages insertObjects:messgeArray atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, messgeArray.count)]];
            //_messages = messgeArray;
            
        } else {
            NSString *maxIndex = firstMessageF.model.message.messageId;
            if (maxIndex == nil) {
            }
            int index = maxIndex.intValue;
            if (index == 0 || index == 1) { // 已经是最后一条了
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.tableView.mj_header endRefreshing];
                });
            } else {
                NSDictionary *param = @{@"gId":self.group.gId,
                                        @"maxIndex":[maxIndex numberValue] == nil ? @0:[maxIndex numberValue],
                                        @"size":@LoadMessageCount};
                [self repullMessage:param viewController:weakSelf firstMessageF:firstMessageF];
            }
        }
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView reloadData];
    }];
}

- (void)repullMessage:(NSDictionary *)param viewController:(ICChnController *)weakSelf firstMessageF:(ICMessageFrame *)firstMessageF
{
    [[ICSocketRequestManager sharedInstance] repullMessageWithObject:param Success:^(id response) {
        // 后台返的消息id是从小到大
        
        NSArray *data = [response objectForKey:@"data"];
        if (data.count > 0) {
            for (NSDictionary *dic in data) {
                [ICMessageHelper messageTypeWithMessage:dic finished:^(ICMessageFrame *messageF) {
                    [ICMessageDatabase saveMessage:messageF.model]; // 统一存储消息
                }];
            }
            [ICMessageDatabase selectMessageWithCount:LoadMessageCount group:weakSelf.group.gId firstMessage:firstMessageF.model.message finish:^(NSArray *array, NSError *error) {
                if (array.count > 0) {
                    [weakSelf.dataList insertObjects:array atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, array.count)]];
                    NSArray* reversedArray = array ;
                    NSMutableArray * messgeArray = [NSMutableArray array];
                    //用来记录上一条消息模型
//                    ICChnModel * lastMessage = nil;
                    for(ICMessageFrame *messageFrame in reversedArray)
                    {
                        ICChnModel * model  = [ICChnModel mj_objectWithKeyValues:[NSDictionary dictionaryWithJsonString:messageFrame.model.message.fileKey]];
                        model.time = [ICMessageHelper timeFormatWithDate2:messageFrame.model.message.date];
                        model.hideTime = NO;//[model.time isEqualToString:lastMessage.time];
                        model.lnk = messageFrame.model.message.lnk;
//                        model.title = [NSString stringWithFormat:@"%@,%@",messageFrame.model.message.messageId,model.title];
                        [messgeArray addObject:model];
//                        lastMessage = model;
                        NSLog(@"hideTime %@",model.hideTime? @"Y":@"N");
                    }
                    
                    [weakSelf.messages insertObjects:messgeArray atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, messgeArray.count)]];
                    [weakSelf.tableView reloadData];
                    [weakSelf.tableView.mj_header endRefreshing];
                }
            }];
            [weakSelf.tableView.mj_header endRefreshing];
        } else {
            [weakSelf.tableView.mj_header endRefreshing];
        }
    } Failure:^(NSError *error, id other) {
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}


- (void)getChanceDataSource {
    WEAKSELF
    [ICMessageDatabase selectMessageWithCount:LoadMessageCount group:self.group.gId firstMessage:nil finish:^(NSArray *array, NSError *error) {
        if (array.count > 0) {
            
            [weakSelf.dataList addObjectsFromArray:array];
            NSArray* reversedArray = array;
             NSMutableArray * messgeArray = [NSMutableArray array];
            //用来记录上一条消息模型
//            ICChnModel * lastMessage = nil;
            for(ICMessageFrame *messageFrame in reversedArray)
            {
              ICChnModel * model  = [ICChnModel mj_objectWithKeyValues:[NSDictionary dictionaryWithJsonString:messageFrame.model.message.fileKey]];
                model.time = [ICMessageHelper timeFormatWithDate2:messageFrame.model.message.date];
                model.hideTime = NO;//[model.time isEqualToString:lastMessage.time];
                model.lnk = messageFrame.model.message.lnk;
//                model.title = [NSString stringWithFormat:@"%@,%@",messageFrame.model.message.messageId,model.title];
                [messgeArray addObject:model];
//                lastMessage = model;
                NSLog(@"hideTime %@",model.hideTime? @"Y":@"N");
            }
            [weakSelf.messages addObjectsFromArray:messgeArray];
            
        } else {
            weakSelf.dataList = nil;
        }
        [weakSelf.tableView reloadData];
        [weakSelf.tableView setContentOffset:CGPointMake(0, self.tableView.contentSize.height - self.tableView.bounds.size.height) animated:YES];
    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"ICChnMessageCell";
    ICChnMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[ICChnMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.message = self.messages[indexPath.row];
    return cell;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataList.count;
}

#pragma mark - <UITableViewDelegate>
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 300;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ICChnModel *message = self.messages[indexPath.row];
    return message.cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ICChnModel *message = self.messages[indexPath.row];
    if (![ICTools stringEmpty:message.lnk]) {
        [self pushCustomViewControllerURL:message.lnk fromViewController:self animated:YES];
    }
}

#pragma mark - Getter

- (NSMutableArray *)dataList {
    if (!_dataList) {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}

- (NSMutableArray *)messages {
    if (!_messages) {
        _messages = [NSMutableArray array];
    }
    return _messages;
}



- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, App_Frame_Width, APP_Frame_Height-64) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = IColor(229, 229, 229);

        [self.view addSubview:_tableView];
    }
    return _tableView;
}

@end
